
#include <Weather.h>

String cityNo = "101270106"; //天气城市代码
// 获取城市天气
WeatherData Weather::getCityWeater()
{
    WeatherData weacherData;
     String URL = "http://d1.weather.com.cn/weather_index/" + cityNo + ".html?_=" + String(now());
//    String URL = "http:// 118.123.207.188/weather_index/" + cityNo + ".html?_=" + String(now());
    WiFiClient client; //新添加
                       //重点1 创建 HTTPClient 对象
    HTTPClient httpClient;

    //重点2 通过begin函数配置请求地址。此处也可以不使用端口号和PATH而单纯的
    // httpClient.begin(URL);
    httpClient.begin(client, URL);

    //设置请求头中的User-Agent
    httpClient.setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
    httpClient.addHeader("Referer", "http://www.weather.com.cn/");

    //启动连接并发送HTTP请求
    int httpCode = httpClient.GET();

    //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
    if (httpCode == HTTP_CODE_OK)
    {
        DynamicJsonDocument doc(1024);

        String str = httpClient.getString();
//        Serial.println(str);
        int indexStart = str.indexOf("weatherinfo\":");
        int indexEnd = str.indexOf("};var alarmDZ");

        String strCityDZ = str.substring(indexStart + 13, indexEnd);

        deserializeJson(doc, strCityDZ);
        JsonObject jsonCityDZ = doc.as<JsonObject>();
        // Serial.println(strCityDZ);

        Serial.println("城市：" + jsonCityDZ["city"].as<String>());
        weacherData.cityName = jsonCityDZ["city"].as<String>();

        Serial.println("天气:" + jsonCityDZ["weather"].as<String>());
        weacherData.weather = jsonCityDZ["weather"].as<String>();
        Serial.println("风向:" + jsonCityDZ["wd"].as<String>());
        weacherData.wind = jsonCityDZ["wd"].as<String>();
        Serial.println("风力:" + jsonCityDZ["wd"].as<String>());
        indexStart = str.indexOf("dataSK =");
        indexEnd = str.indexOf(";var dataZS");
        String strDataSK = str.substring(indexStart + 8, indexEnd);
        Serial.println(strDataSK);
        deserializeJson(doc, strDataSK);
        JsonObject jsonDataSK = doc.as<JsonObject>();
        Serial.println("PM2.5:" + jsonDataSK["aqi"].as<String>());
        weacherData.pm25V = jsonDataSK["aqi"].as<int>();
        Serial.println("温度：" + jsonDataSK["temp"].as<String>());
        weacherData.temp = jsonDataSK["temp"].as<String>();
        weacherData.humidity = jsonDataSK["sd"].as<String>();

        Serial.println("获取成功");
    }
    else
    {
        Serial.println("请求城市天气错误：");
        Serial.print(httpCode);
    }

    //关闭ESP8266与服务器连接
    httpClient.end();

    return weacherData;
}
